package com.heima.comment.service.impl;

import com.heima.client.UserClient;
import com.heima.comment.dto.CommentDto;
import com.heima.comment.dto.CommentSaveDto;
import com.heima.comment.entity.ApComment;
import com.heima.comment.service.ICommentService;
import com.heima.common.dto.ResponseResult;
import com.heima.common.dto.User;
import com.heima.common.enums.AppHttpCodeEnum;
import com.heima.common.util.UserThreadLocal;
import com.heima.domain.ApUser;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
public class CommentServiceImpl implements ICommentService {

    @Autowired
    private MongoTemplate mongoTemplate;

    @Autowired
    private UserClient userClient;

    @Override
    public ResponseResult saveComment(CommentSaveDto dto) {
        User user = UserThreadLocal.get();
        //用户登录后可以对文章发表评论
        if (user == null || user.getUserId() == 0) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }

        //评论内容不为空且不超过140字
        if (StringUtils.isBlank(dto.getContent()) || dto.getContent().length() > 140) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        ResponseResult<ApUser> responseResult = userClient.getUserById(user.getUserId());
        ApUser apUser = responseResult.getData();

        ApComment apComment = new ApComment();
        apComment.setUserId(user.getUserId());
        apComment.setUserName(apUser.getName());
        apComment.setImage(apUser.getImage());
        apComment.setArticleId(dto.getArticleId());
        apComment.setContent(dto.getContent());
        apComment.setLikes(0); //当前这个评论收到的点赞数
        apComment.setRepay(0); //当前这个评论收到的回复数
        apComment.setCreatedTime(new Date());
        mongoTemplate.save(apComment);
        return ResponseResult.okResult();
    }

    @Override
    public ResponseResult loadComment(CommentDto dto) {
        if (dto.getSize() == null || dto.getSize() <= 0 || dto.getSize() >= 50) {
            dto.setSize(10);
        }
        //按照评论发布时间倒序排列  createTime  desc
        //分页查询  limit
        // 查询条件：articleId  createTime<=minDate  分页
        Criteria criteria = Criteria.where("articleId").is(dto.getArticleId()).and("createdTime").lt(dto.getMinDate());
        Query query = new Query(criteria);
        query.with(Sort.by(Sort.Direction.DESC,"createdTime"));
        query.limit(dto.getSize());
        List<ApComment> commentList = mongoTemplate.find(query, ApComment.class);
        return ResponseResult.okResult(commentList);
    }
}
